package com.dengke.springsecurity.model;

import java.util.ArrayList;
import java.util.List;

public class CartInfo {
	private int orderNum;
	private CustomerInfo customerInfo;
	private final List<CartLineInfo>cartLines=new ArrayList<CartLineInfo>();
	
	public CartInfo() {
	}

	public int getOrderNum() {
		return orderNum;
	}

	public void setOrderNum(int orderNum) {
		this.orderNum = orderNum;
	}

	public CustomerInfo getCustomerInfo() {
		return customerInfo;
	}

	public void setCustomerInfo(CustomerInfo customerInfo) {
		this.customerInfo = customerInfo;
	}

	public List<CartLineInfo> getCartLines() {
		return cartLines;
	}
	private CartLineInfo findLineByCode(String code) {
		for (CartLineInfo lineInfo : this.cartLines) {
			if(lineInfo.getProductInfo().getCode().equals(code)){
				return lineInfo;
			}
		}
		return null;
	}
	
	/***
	 * 添加product
	 * @param productInfo
	 * @param quantity
	 */
	public void addProduct(ProductInfo productInfo,int quantity){
		CartLineInfo line =this.findLineByCode(productInfo.getCode());
		//如果添加的商品在购物车中不存在，则直接在
		//购物车中添加cartlineinfo
		if (line==null) {
			line=new CartLineInfo();
			line.setQuantity(0);
			line.setProductInfo(productInfo);
			this.cartLines.add(line);
		}
		int newQuantity=line.getQuantity()+quantity;
		if (newQuantity<=0) {
			this.cartLines.remove(line);
		}else {
			line.setQuantity(newQuantity);
		}
	}
	
	public void validate() {
		
	}
	
	/***
	 * update product quantity
	 * @param code
	 * @param quantity
	 */
	public void updateProduct(String code,int quantity) {
		CartLineInfo line=this.findLineByCode(code);
		if (line!=null) {
			if (quantity<=0) {
				this.cartLines.remove(line);
			}else {
				line.setQuantity(quantity);
			}
		}
	}
	
	public void removeProduct(ProductInfo productInfo) {
		CartLineInfo line=this.findLineByCode(productInfo.getCode());
		if (line!=null) {
			this.cartLines.remove(line);
		}
	}
	
	public boolean isEmpty() {
		return this.cartLines.isEmpty();
	}
	
	public boolean isValidCustomer() {
		return this.customerInfo!=null&&this.customerInfo.isValid();
	}
	
	public int getQuantityTotal() {
		int quantity=0;
		for (CartLineInfo lineInfo : this.cartLines) {
			quantity+=lineInfo.getQuantity();
		}
		return quantity;
	}
	
	public double getAmountTotal() {
		double total=0;
		for (CartLineInfo lineInfo : this.cartLines) {
			total+=lineInfo.getAmount();
		}
		return total;
	}
	
	public void updateQuantity(CartInfo cartForm) {
		if (cartForm!=null) {
			List<CartLineInfo>lines=cartForm.getCartLines();
			for (CartLineInfo lineInfo : lines) {
				this.updateProduct(lineInfo.getProductInfo().getCode(), lineInfo.getQuantity());
			}
		}
	}
}
